#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define MAX_OP 10

typedef struct Stack{
    int *data;
    int size, top;
}Stack;

Stack *initStack(int n){
    Stack *s =(Stack *)malloc(sizeof(Stack));
    s->data = (int *)malloc(sizeof(int) * n);
    s->size = n;
    s->top = -1;
    return s;
}

int empty(Stack *s){
    return s->top == -1;
}

void clearStack(Stack *s){
    if(s == NULL) return;
    free(s->data);
    free(s);
    return;
}

int top(Stack *s){
    if(empty(s)) return -1;
    return s->data[s->top];
}

int push(Stack *s, int val){
    if(s->top + 1 == s->size) {
        printf("stack is full.\n");
        return 0;
    }
    s->top += 1;
    s->data[s->top] = val;
    return 1;
}

int pop(Stack *s){
    if(empty(s)) return 0;
    s->top -= 1;
    return 1;
}

void outputStack(Stack *s){
    printf("Stack: ");
    for(int i = s->top; i >= 0; --i){
        printf("%4d", s->data[i]);
    }
    printf("\n\n");
    return;
}

int main(){
    srand(time(0));
    Stack *s = initStack(5);
    for(int i = 0; i < MAX_OP; i++){
        // 0 pop, 1,2 push
        int op = rand() % 3; 
        int val = rand() % 100;
        switch (op) {
            case 0:
                printf("pop stack, top is: %d\n", top(s));
                pop(s);
                break;
            case 1:
            case 2:
                printf("push %d to stack\n", val);
                push(s, val);
                break;
        }
        outputStack(s);
    }
    
    clearStack(s);
    return 0;
}